<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\User;
use fast\Random;
use think\Validate;

/**
 * 会员登录接口
 */
class Login extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 微信登录
     * @param int $url 当前页面url
     * @param int $userid 分享人的userid没有传0或null
     * @ApiReturn   ()
     */
    public function wx_login(){
        $this_url = $this->request->get('url');
        $userid = $this->request->get('userid');
       /* $userid = 0;*/
        if(isset($this_url)){
            session('url',$this_url);
            //$userid = getQuerystr($this_url,'userid');
        }

        if($userid && $userid != null){
            $tiaozhuan_url = urlencode($this->domain.'/api/login/getAccessToken?userid='.$userid);
        }else{
            $tiaozhuan_url = urlencode($this->domain.'/api/login/getAccessToken');
        }
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1b231da6c9445019&redirect_uri='.$tiaozhuan_url.'&response_type=code&scope=snsapi_userinfo&#wechat_redirect';
        header("Location:".$url);exit;
    }
    public  function getAccessToken()
    {
        $code = $_REQUEST['code'];
        if(isset($_REQUEST['userid'])){
            $userid = $_REQUEST['userid'];
        }
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1b231da6c9445019&secret=cd8afaca3c03d30b149d2415ca5759fb&code='.$code.'&grant_type=authorization_code';
        $result =  file_get_contents($url);
        $result_arr = json_decode($result,true);
        if(!isset($result_arr['access_token'])){
            $this->wx_login();
        }
        $token = $result_arr['access_token'];
        $openid = $result_arr['openid'];
        if($openid){
            $list = User::where('openid',$openid)->find();
            $user_token = Random::uuid();
            if($list){
                //如果用户已存在，直接登陆
                User::where('openid',$openid)->update(['token'=>$user_token]);
                //判断是否绑定过手机号，如果没有，跳转绑定手机号页面
                if($list['mobile'] == ''){
                    header('location:'.$this->domain.'/h5/html/bindphone.html?token='.$user_token);exit;
                }else{
                    if(session('url')){
                        $location_url = session('url');
                        $res = strstr($location_url,'?');
                        if($res){
                            $location_url = $location_url.'&token='.$user_token;
                        }else{
                            $location_url = $location_url.'?token='.$user_token;
                        }
                        session('url',null);
                        header('location:'.$location_url);
                        exit;
                    }else{
                        header('location:'.$this->domain.'/h5/html/index.html?token='.$user_token);exit;
                    }
                }
            }else{
                $url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
                $result1 =  file_get_contents($url1);
                $result_arr1 = json_decode($result1,true);
                //保存用户头像到本地
                //$headimgurl = put_file_from_url_content($result_arr1['headimgurl'], $result_arr1['openid'],'uploads/headimage/');
                //print_r($result_arr1);exit;
                $user_info = [
                    'avatar' => $result_arr1['headimgurl'],
                    'username' =>$result_arr1['nickname'],
                    'openid' => $result_arr1['openid'],
                    'createtime' => time(),
                    'token' => $user_token,
                ];
                if(isset($userid)){
                    $parent_info = User::where('id',$userid)->count();
                    if($parent_info){
                        $user_info['parent_id'] =$userid;
                    }
                }
                $uid= User::insertGetId($user_info);//user表
                //跳转绑定手机号页面
                header('location:'.$this->domain.'/h5/html/bindphone.html?token='.$user_token);exit;
            }
           /* if(session('url')){
                $location_url = session('url');
                $res = strstr($location_url,'?');
                if($res){
                    $location_url = $location_url.'&token='.$user_token;
                }else{
                    $location_url = $location_url.'?token='.$user_token;
                }
                session('url',null);
                header('location:'.$location_url);
                exit;
            }else{
                header('location:'.$this->domain.'?token='.$user_token);exit;
            }*/
        }
    }
    public function emoji_encode($nickname){
        $strEncode = '';
        $length = mb_strlen($nickname,'utf-8');
        for ($i=0; $i < $length; $i++) {
            $_tmpStr = mb_substr($nickname,$i,1,'utf-8');
            if(strlen($_tmpStr) >= 4){
                $strEncode .='.';
            }else{
                $strEncode .= $_tmpStr;
            }
        }
        return $strEncode;
    }
    public function check_session(){
        if(session('userid')){
            $res = User::where('id',session('userid'))->count();
            if($res){
                $data = [
                    'code' => 0
                ];
            }else{
                $data = [
                    'code' => 1
                ];
            }
        }else{
            $data = [
                'code' => 1
            ];
        }
        return json($data);
    }
}
